#ifndef __LOCK_FREE_QUEUE_H_
#define __LOCK_FREE_QUEUE_H_
#include <atomic>
namespace xrtc
{
    // 无锁队列满足的条件
    // 1.一个生产者，一个消费者
    // 2.指针的操作使原子性的
    template <typename T>
    class LockFreeQueue
    {

    private:
        struct Node
        {
            T value;
            Node *next;
            Node(const T &value) : value(value), next(nullptr) {}
        };
        Node *first;
        Node *divider; // 中间
        Node *last;
        std::atomic<int> size_;

    public:
        LockFreeQueue()
        {

            first = divider = last = new Node(T());
            size_ = 0;
        }
        ~LockFreeQueue()
        {
            while (first != nullptr)
            {
                Node *temp = first;
                first = first->next;
                delete temp;
            }
            size_ = 0;
        }
        void Produce(const T &t)
        {
            last->next = new Node(t);
            last = last->next;
            ++size_;
            while (divider != first)
            {
                Node *temp = first;
                first = first->next;
                delete temp;
            }
        }
        bool Consume(T *result)
        {
            if (divider != last)
            {
                *result = divider->next->value;
                divider = divider->next;
                --size_;
                return true;
            }
            return false;
        }
        bool Empty()
        {
            return size_ == 0;
        }
        int Size()
        {
            return size_;
        }
    };

} // namespace xrtc

#endif